package com.sinry.common.core.advices;

import com.sinry.common.core.annotations.ResponseHandler;
import com.sinry.common.core.domain.vo.base.R;
import lombok.NonNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

/**
 * @author linxinlei
 * @project sinry-cloud
 * @description 响应信息处理
 * @date 2022/5/23
 **/
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                @NonNull MethodParameter returnType,
                                @NonNull MediaType selectedContentType,
                                @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                @NonNull ServerHttpRequest request,
                                @NonNull ServerHttpResponse response) {

        Method method = returnType.getMethod();
        if (ObjectUtils.isEmpty(method)) {
            return body;
        }
        Class<?> declaringClass = method.getDeclaringClass();
        ResponseHandler annotation = declaringClass.getAnnotation(ResponseHandler.class);
        if (ObjectUtils.isEmpty(annotation)) {
            return body;
        }
        return R.ok(body);
    }
}
